/*
 * Spinner.cpp
 *
 *  Created on: 06-12-2010
 *      Author: Przemek
 */

#include "gui/UIManager.hpp"
#include "gui/GLFont.hpp"
#include "gui/Spinner.hpp"
#include "gui/ClipArea.hpp"
#include "utils/GLUtils.hpp"
#include "pch.hpp"
using namespace std;
using namespace boost;

const float Spinner::ARROW_WIDTH = 20.0f;

Spinner::Spinner(const Range<int>& range, int value) :
	value(range, value), increaseArrow(new ArrowButton()), decreaseArrow(new ArrowButton(180))
{
	add(increaseArrow);
	add(decreaseArrow);

	setOpaque(false);

	increaseArrow->addMouseListener(this);
	decreaseArrow->addMouseListener(this);
	increaseArrow->addKeyListener(this);
	decreaseArrow->addKeyListener(this);
}

void Spinner::draw(const ClipArea& clipArea)
{
	UIManager::getInstance().getSpinnerBackgroundColor().setGLState();
	GLUtils::drawRectangle(Vector(0, 0), getSize());

	setButtonBounds();
	Container::draw(clipArea);
	clipArea.setGLClipArea();

	UIManager::getInstance().getSpinnerTextColor().setGLState();
	const GLFont& font = UIManager::getInstance().getGUIFont();
	font.begin();
	const string& text = lexical_cast<string> (value.getValue());
	font.drawTextAt(text, getCenteredTextLeftCornerPosition(text));
	font.end();
}

void Spinner::setButtonBounds()
{
	geometry::Rectangle upperArrowBounds;
	upperArrowBounds.setPosition(Vector(getSize().getWidth() - ARROW_WIDTH, 0.0f));
	upperArrowBounds.setSize(Dimension(ARROW_WIDTH, getSize().getHeight() / 2 - 1));

	increaseArrow->setBounds(upperArrowBounds);
	decreaseArrow->setBounds(upperArrowBounds.translate(Vector(0.0f, getSize().getHeight() / 2 + 1)));
}

void Spinner::mousePressed(const MouseListener::EventArguments& arguments)
{
	if(arguments.getSource() == increaseArrow)
	{
		value.changeBy(1);
	}
	else if(arguments.getSource() == decreaseArrow)
	{
		value.changeBy(-1);
	}
}

void Spinner::keyPressed(const KeyListener::EventArguments& arguments)
{
	if(arguments.getKey() == SDLK_UP)
	{
		value.changeBy(1);
	}
	else if(arguments.getKey() == SDLK_DOWN)
	{
		value.changeBy(-1);
	}
}
